package com.example.featuresdk.dao

import androidx.room.*
import com.example.featuresdk.model.Book
import kotlinx.coroutines.flow.Flow

//Write asynchronous DAO queries
//https://developer.android.google.cn/training/data-storage/room/async-queries#flow-coroutines
@Dao
interface BookDao {

    //https://developer.android.google.cn/training/data-storage/room/async-queries#observable
    @Query("select * from book")
    fun getAll(): Flow<List<Book>>

    @Query("select count(1) from book where name like '%Android%'")
    fun getCount(): Flow<Int>

    @Query("select * from book where isbn = :isbn LIMIT 1")
    fun get(isbn: String): Flow<Book>

    //The insert/update/delete methods should not execute on the main thread, use "suspend" to enforce this.
    //otherwise java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
    //https://developer.android.google.cn/training/data-storage/room/async-queries#one-shot
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(vararg books: Book)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(books: List<Book>)

    @Delete
    suspend fun delete(book: Book)

    @Query("DELETE FROM book where isbn = :isbn")
    suspend fun delete(isbn: String)

    @Query("DELETE FROM book")
    suspend fun deleteAll()

    @Update
    suspend fun update(book: Book)

    @Update(entity = Book::class)
    suspend fun update(price: Price)

    class Price (var isbn: String, var price: String)
}